<template>
  <!-- 选择编辑/新建版本 -->
  <div class="align-center">
    <el-upload drag action="#" :limit="1" :before-upload="uploadBeforeMore" :auto-upload="true" :show-file-list="false">
      <div v-loading="loading">
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
          <br />
          文件总大小不超过 {{ maxSize }} MB
          <span v-show="acceptsList.message">
            ，仅支持
            <span style="color:red">{{ acceptsList.message }}</span>
            格式
          </span>
        </div>
      </div>
    </el-upload>
    <div class="upload-file-list">
      <div v-for="item in defaultUploadFiles" :key="item.fileUrl" class="upload-file-list-item neu-ellipse">
        <!--  default-items -->
        <el-icon @click="removeDefaultFile(item)">
          <circle-close />
        </el-icon>
        {{ item.fileName }}
      </div>
      <div v-for="item in uploadFiles" :key="item.uid" class="upload-file-list-item neu-ellipse">
        <el-icon @click="removeFile(item)">
          <circle-close />
        </el-icon>
        {{ item.name }}
      </div>
    </div>
  </div>
</template>
<script>
import ObsClient from 'esdk-obs-browserjs'
export default {
  name: 'DialogUpload',
  emits: ['update:modelValue'],
  props: {
    type: {
      type: String,
      default: 'WZ'
    },
    modelValue: {
      type: Object,
      default: () => ({}),
    },
    maxSize: {
      type: Number,
      default: 300
    }
  },
  data () {
    return {
      loading: false,
      uploadFiles: [],
      defaultUploadFiles: [],
      access_key_id: '43I9JLFQGK4HTIVS4HHJ',
      secret_access_key: 'Y0CfSExq0PmgokPwvu415kg6S5vEBWfeZRhaqMhq',
      bucketName: 'neuedu-expo-test', // 桶名
      serverUrl: 'https://obs.cn-north-4.myhuaweicloud.com', // 服务器地址
      server: 'obs.cn-north-4.myhuaweicloud.com',
      accepts: {
        SP: {
          accept: ['.mp4'],
          hint: '仅支持 mp4 媒体格式',
          message: 'mp4'
        },
        YP: {
          accept: ['.mp3', '.ogg'],
          hint: '仅支持 mp3，ogg 媒体格式'
        },
        WD: {
          accept: ['.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.pdf', '.txt'],
          hint: '仅支持doc，docx，xls，xlsx，ppt，pptx，pdf，txt文档格式'
        },
        TP: {
          accept: ['.jpg', '.png', '.jpeg', '.gif', '.bmp'],
          hint: '仅支持 jpg，png，jpeg，gif，bmp 文档格式'
        },
        QTZY: {
          accept: ['.zip', '.rar'],
          hint: '仅支持 zip，rar 压缩格式'
        },
        MD: {
          accept: ['.md'],
          hint: '仅支持 md 文件格式'
        },
        WZ: {
          accept: ['*'],
          hint: ''
        },
      },
      hintlist: []
    }
  },
  computed: {
    acceptsList () {
      let _list = []
      _list = _list.concat(this.accepts[this.type].accept)
      return {
        accept: _list,
        hint: '仅支持 ' + _list.join('，') + ' 格式',
        message: this.accepts[this.type].message ? this.accepts[this.type].message : ''
      }
    },
    defaultFiles () {
      return [this.modelValue]
    }
  },
  watch: {
    defaultFiles: {
      handler (val) {
        this.defaultUploadFiles = [...(val || [])]
        this.uploadFiles = []
      },
      immediate: true,
      deep: true,
    },
  },
  mounted () {
    this.defaultUploadFiles = [...(this.defaultFiles || [])]
  },
  methods: {
    timestampToTime () {
      var date = new Date() //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + '/'
      var M =
        (date.getMonth() + 1 < 10
          ? '0' + (date.getMonth() + 1)
          : date.getMonth() + 1) + '/'
      var D =
        (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + '/'
      return Y + M + D
    },
    timestampTime () {
      var date = new Date() //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear()
      var M =
        date.getMonth() + 1 < 10
          ? '0' + (date.getMonth() + 1)
          : date.getMonth() + 1
      var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      var h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
      var m =
        date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      var s =
        date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      return Y + M + D + h + m + s
    },
    uploadBeforeMore (file) {
      var date = new Date()
      // 取文件名
      const n = file.name.lastIndexOf(".")
      const fileName = file.name.substr(0, n)
      // 文件后缀
      const type = file.name.substr(n + 1, file.name.length)
      if (this.type !== 'WZ' && this.acceptsList.accept.indexOf('.' + type) < 0) {
        this.$message({
          type: 'warning',
          message: this.acceptsList.hint + '！'
        })
        return false
      }
      const timestampFileName =
        this.timestampToTime(date) +
        fileName +
        '_' +
        this.timestampTime(date) +
        '.' +
        type
      if (file.size / 1024 / 1024 >= this.maxSize) {
        this.$message({
          type: 'warning',
          message: `单文件大小不超过 ${this.maxSize} MB！`,
        })
      } else {
        let FileExt = file.name.replace(/.+\./, '.')
        if (FileExt.toLowerCase() === '.md') {
          if (file.size / 1024 / 1024 >= 1) {
            this.$message({
              type: 'warning',
              message: 'Markdown资源大小不能超过1M！',
            })
            return false
          }
        }
        if (file.name.length > 200) {
          this.$message({
            type: 'warning',
            message: '资源名称不能超过200个字符！',
          })
        } else {
          let sum = 0
          this.uploadFiles.forEach((t) => {
            sum += t.size
          })
          if (sum / 1024 / 1024 >= this.maxSize) {
            this.$message({
              type: 'warning',
              message: `文件总大小不超过 ${this.maxSize} MB`,
            })
          } else {
            this.loading = true
            // 上传华为云
            var obsClient = new ObsClient({
              access_key_id: this.access_key_id,
              secret_access_key: this.secret_access_key,
              server: this.serverUrl,
            })
            obsClient.putObject(
              {
                Bucket: this.bucketName, // 桶名
                Key: timestampFileName, // 文件名
                SourceFile: file,
                ContentType: 'text/plain',
              },
              (err, result) => {
                if (err) {
                  this.$message.error({
                    message: '上传失败，请重试',
                  })
                  this.loading = false
                } else {
                  if (result.CommonMsg.Status < 300) {
                    // 上传成功后，文件地址
                    const fileUrl =
                      'https://' +
                      this.bucketName +
                      '.' +
                      this.server +
                      '/' +
                      timestampFileName
                    this.$emit('update:modelValue', {
                      fileName: file.name,
                      fileUrl: fileUrl
                    })
                    this.$message.success({
                      message: '文件上传成功！',
                    })
                    this.loading = false
                  } else {
                    this.$message.error({
                      message: '上传失败，请重试',
                    })
                    this.loading = false
                  }
                }
              }
            )
          }
        }
      }
      return false
    },
    removeFile (item) {
      this.uploadFiles = this.uploadFiles.filter((t) => t.uid !== item.uid)
      this.$emit('update:modelValue', {
        fileName: '',
        fileUrl: ''
      })
    },
    removeDefaultFile (item) {
      this.defaultUploadFiles = this.defaultUploadFiles.filter(
        (t) => t.fileId !== item.fileId
      )
      this.$emit('update:modelValue', {
        fileName: '',
        fileUrl: ''
      })
    },
  },
}
</script>
<style lang="scss" scoped>
@import '~/styles/base.scss';

:deep(.drag) {
  width: 395px;
  border-radius: 2px;
  text-align: left;
  cursor: pointer;
  display: inline-block;
  background: rgba(0, 0, 0, 0.05);

  img {
    margin: 0 15px;
  }

  span {
    width: calc(100% - 50px);
  }

  .el-icon-error {
    font-size: 18px;
    color: red;
    margin-right: 15px;
  }

  .el-upload {
    display: unset !important;

    .el-upload-dragger {
      width: 100%;
      height: 40px;
      text-align: left;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }
}

:deep(.el-tabs__nav-wrap::after) {
  display: none;
}

:deep(.el-tabs__header) {
  padding: 0 202px;
}

:deep(.el-upload-dragger .el-upload__text) {
  line-height: 22px;
}

.upload-file-tip {
  width: 360px;
  margin: 0 auto;
  text-align: left;
  line-height: 22px;
}

.upload-file-list {
  width: 100%;

  .upload-file-list-item {
    width: 360px;
    margin: 0 auto 4px;
    text-align: left;
    position: relative;
    line-height: 26px;
    padding: 0 20px 0 5px;
    border-radius: 2px;
    cursor: pointer;
    background: rgba($color: $neu-primary-color, $alpha: 0.05);

    &.default-items {
      background: rgba($color: $neu-orange-color, $alpha: 0.05);
    }

    i {
      display: none;
      position: absolute;
      right: 3px;
      top: 6px;
    }

    &:hover {
      background: $neu-primary-color;
      color: $neu-white-color;

      &.default-items {
        background: $neu-orange-color;
      }

      i {
        display: block;
      }
    }
  }
}

.neu-ellipse {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
